package com.struts.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts.utils.UploadUtil;


public class UploadAction extends ActionSupport{
	
	private File resource ; //客户端上传的文件
	private String resourceContentType ; //上传文件的类型
	private String resourceFileName ; //上传文件的名称
	private InputStream inputStream ; //文件下载输入流
	
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public File getResource() {
		return resource;
	}
	public void setResource(File resource) {
		this.resource = resource;
	}
	public String getResourceContentType() {
		return resourceContentType;
	}
	public void setResourceContentType(String resourceContentType) {
		this.resourceContentType = resourceContentType;
	}
	public String getResourceFileName() {
		return resourceFileName;
	}
	public void setResourceFileName(String resourceFileName) {
		this.resourceFileName = resourceFileName;
	}
	/**
	 * 文件上传
	 * @return
	 */
	public String upload() {
		//上传文件，返回文件保存路径
		String filePath = UploadUtil.saveUploadFile(resource, this.resourceFileName) ;
		//将上传的文件名称存入session中
		ServletActionContext.getRequest().getSession().setAttribute("fileName", this.resourceFileName) ;
		//将上传的文件的全路径（包含文件名）存入到session中
		ServletActionContext.getRequest().getSession().setAttribute("filePath", filePath + this.resourceFileName) ;
		return "upload" ;
	}
	/**
	 * 文件下载
	 * @throws UnsupportedEncodingException 
	 */
	public String download() throws Exception {
		//获取下载文件名称
		String fileName = ServletActionContext.getRequest().getSession().getAttribute("fileName").toString() ;
		//获取下载文件路径
		String filePath = ServletActionContext.getRequest().getSession().getAttribute("filePath").toString() ;
		//将fileName进行转码，并放入到map栈中，以便返回结果视图中获取该文件名称
		fileName = URLEncoder.encode(fileName, "utf-8") ;
		ActionContext.getContext().put("fileName", fileName) ;
		//将准备下载的文件放入到IO流中
		inputStream = new FileInputStream(filePath) ;
		return "download" ;
	}

}
